//
//  RegistViewController.m
//  Ufan
//
//  Created by yangqingluo on 15/10/17.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "RegistViewController.h"


#define NUMBER @"0123456789"

#define kCodeLength           0x06

#define kPasswordLengthMin           0x06
#define kPasswordLengthMax           0x10

@interface RegistViewController ()

@property (strong, nonatomic) IBOutlet UITextField *usernameTextField; //用户名输入（手机号码）
@property (strong, nonatomic) IBOutlet UITextField *codeTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UITextField *pwdAgainTextField;
@property (strong, nonatomic) IBOutlet UIButton *sureButton;
@property (strong, nonatomic) IBOutlet UIButton *getCodeButton;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBarButtonItem];
    
    
    _usernameTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _usernameTextField.layer.borderWidth = 0.8f;
//    _usernameTextField.layer.cornerRadius = 10.0f;
    
    _codeTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _codeTextField.layer.borderWidth = 0.8f;
    
    _passwordTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _passwordTextField.layer.borderWidth = 0.8f;
//    _passwordTextField.layer.cornerRadius = 10.0f;
    
    _pwdAgainTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _pwdAgainTextField.layer.borderWidth = 0.8f;
//    _pwdAgainTextField.layer.cornerRadius = 10.0f;
    
    _getCodeButton.layer.borderColor = [UIColor blackColor].CGColor;
    _getCodeButton.layer.borderWidth = 0.8f;
    _getCodeButton.layer.masksToBounds = YES;
}

- (void)setupBarButtonItem{
    self.title = @"账户注册";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)waitForGettingCodeAgain:(NSNumber *)timeToGetCodeAgain{
    if ([timeToGetCodeAgain intValue]) {
        _getCodeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.getCodeButton.enabled = NO;
        [self.getCodeButton setTitle:[NSString stringWithFormat:@"%@秒",timeToGetCodeAgain] forState:UIControlStateDisabled];
        timeToGetCodeAgain=[NSNumber numberWithInt:([timeToGetCodeAgain intValue]-1)];
        [self performSelector:@selector(waitForGettingCodeAgain:) withObject:timeToGetCodeAgain afterDelay:1.0];
    }
    else{
        _getCodeButton.layer.borderColor = [UIColor blackColor].CGColor;
        self.getCodeButton.enabled = YES;
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self dismissKeyBoard];
}

-(void)dismissKeyBoard{
    [self.view endEditing:YES];
}


#pragma mark---------UITextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isEqual:self.usernameTextField]) {
        NSCharacterSet *notNumber=[[NSCharacterSet characterSetWithCharactersInString:NUMBER]invertedSet];
        NSString *string1 = [[string componentsSeparatedByCharactersInSet:notNumber]componentsJoinedByString:@""];
        return ([string isEqualToString:string1] && range.location < kPhoneNumberLength);
    }
    else if ([textField isEqual:self.passwordTextField] || [textField isEqual:self.pwdAgainTextField]){
        
        return (range.location < kPasswordLengthMax);
    }
    else if ([textField isEqual:self.codeTextField]){
        return (range.location < kCodeLength);
    }
    
    return YES;
}




- (IBAction)buttonClick:(id)sender {
    [self dismissKeyBoard];
    
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
            //确定提交
        case 10:{
            if (self.usernameTextField.text.length != kPhoneNumberLength) {
                [self.view makeToast:@"手机号输入不正确" duration:QKToastDuration position:QKToastPoint];
                
                return;
            }
            else if (self.codeTextField.text.length != kCodeLength) {
                [self.view makeToast:@"请输入6位验证码" duration:QKToastDuration position:QKToastPoint];
                
                return;
            }
            else if (![self.passwordTextField.text isEqualToString:self.pwdAgainTextField.text]){
                [self.view makeToast:@"两次密码输入不一致" duration:QKToastDuration position:QKToastPoint];
                
                return;
            }
            else if (self.passwordTextField.text.length < kPasswordLengthMin || self.passwordTextField.text.length > kPasswordLengthMax) {
                [self.view makeToast:[NSString stringWithFormat:@"密码长度应为 %d - %d",kPasswordLengthMin,kPasswordLengthMax] duration:QKToastDuration position:QKToastPoint];
                
                return;
            }
            else{
                [self showHudInView:self.view hint:@"注册中..."];
                
                [QKHttpManager registWithPhone:self.usernameTextField.text password:sha1(self.passwordTextField.text) identifyCode:self.codeTextField.text andToken:nil completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    
                    if (!error) {
                        if ([object isKindOfClass:[NSDictionary class]]) {
                            if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_SUCCESS) {
                                
                                [self.navigationController.view makeToast:@"注册成功，请登录" duration:QKToastDuration position:QKToastPoint];
                                [self goBack];
                                
                                return;
                            }
                            else if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_ERROR){
                                
                            }
                            
                            [self.view makeToast:[(NSDictionary *)object objectForKey:@"msg"] duration:QKToastDuration position:QKToastPoint];
                            return;
                        }
                        else{
                            [self.view makeToast:@"出错" duration:QKToastDuration position:QKToastPoint];
                        }
                    }
                    else{
                        [self.view makeToast:@"网络出错" duration:QKToastDuration position:QKToastPoint];
                    }
                    
                    
                }];
                
                
            }
            
           
        }
            break;
          
            //阅读协议
        case 11:{
            button.selected = !button.selected;
            self.sureButton.enabled = button.selected;
        }
            break;
            
            //获取验证码
        case 12:{
            if (self.usernameTextField.text.length != kPhoneNumberLength) {
                [self.view makeToast:@"手机号输入不正确" duration:QKToastDuration position:QKToastPoint];
                
                return;
            }
            else{
                [self showHudInView:self.view hint:@"获取验证码..."];
                
                [QKHttpManager getIdentifyCodeWithPhone:self.usernameTextField.text andIsRegistered:NO completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    
                    if (!error) {
                        if ([object isKindOfClass:[NSDictionary class]]) {
                            if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_SUCCESS) {
                                [self waitForGettingCodeAgain:@60];
                            }
                            else if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_ERROR){
                                
                            }
                            
                            [self.view makeToast:[(NSDictionary *)object objectForKey:@"msg"] duration:QKToastDuration position:QKToastPoint];
                            return;
                        }
                        else{
                            [self.view makeToast:@"出错" duration:QKToastDuration position:QKToastPoint];
                        }
                    }
                    else{
                        [self.view makeToast:@"网络出错" duration:QKToastDuration position:QKToastPoint];
                    }
                    
                    
                }];
            }
        }
            break;
            
        default:
            break;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
